/**
 * 本地存储工具
 */

// 存储键名常量
export const STORAGE_KEYS = {
  TOKEN: "token",
  USER_INFO: "userInfo",
  SEARCH_HISTORY: "searchHistory",
  BROWSE_HISTORY: "browseHistory",
} as const;

/**
 * 设置存储
 */
export const setStorage = (key: string, value: any): void => {
  try {
    uni.setStorageSync(key, JSON.stringify(value));
  } catch (error) {
    console.error("设置存储失败:", error);
  }
};

/**
 * 获取存储
 */
export const getStorage = <T = any>(
  key: string,
  defaultValue?: T
): T | null => {
  try {
    const value = uni.getStorageSync(key);
    if (value) {
      return JSON.parse(value) as T;
    }
    return defaultValue || null;
  } catch (error) {
    console.error("获取存储失败:", error);
    return defaultValue || null;
  }
};

/**
 * 删除存储
 */
export const removeStorage = (key: string): void => {
  try {
    uni.removeStorageSync(key);
  } catch (error) {
    console.error("删除存储失败:", error);
  }
};

/**
 * 清空存储
 */
export const clearStorage = (): void => {
  try {
    uni.clearStorageSync();
  } catch (error) {
    console.error("清空存储失败:", error);
  }
};

/**
 * Token相关操作
 */
export const tokenStorage = {
  set: (token: string) => setStorage(STORAGE_KEYS.TOKEN, token),
  get: () => getStorage<string>(STORAGE_KEYS.TOKEN),
  remove: () => removeStorage(STORAGE_KEYS.TOKEN),
};

/**
 * 用户信息相关操作
 */
export const userInfoStorage = {
  set: (userInfo: any) => setStorage(STORAGE_KEYS.USER_INFO, userInfo),
  get: () => getStorage(STORAGE_KEYS.USER_INFO),
  remove: () => removeStorage(STORAGE_KEYS.USER_INFO),
};
